package com.tbq.game.service.socket.netty

import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

class ClientHandler : SimpleChannelInboundHandler<String>() {
    override fun channelRead0(ctx: ChannelHandlerContext?, msg: String?) {
        NettyLog.e("收到信息：$msg")
        if (NettyClient.keepaliveFlag != msg) {
            ctx?.channel()?.writeAndFlush(NettyClient.endFlag)   // 发送心跳消息
            val listener = NettyClient.oldListener
            if (listener != null) listener.onEventMessage("$msg")
        }

    }

    override fun channelInactive(ctx: ChannelHandlerContext?) {
        NettyClient.loopConnect(ctx?.channel(), Exception("网络不稳定，channelInactive 和服务器连接失败！"))
    }

    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        NettyClient.loopConnect(ctx?.channel(), Exception("网络不稳定，channelInactive 和服务器连接失败！"))
    }
}